package com.itlaobing.binary;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.Collection;

@WebServlet("/multi/part/*")
@MultipartConfig
public class MultipartServlet extends HttpServlet { //理解multipart/form-data并在Servlet中获取multipart/form-data中的数据
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // javax.servlet.http.Part类型的实例表示 multipart/form-data 表单上的一个 part (即其中的一条 form-data )
        Collection<Part> parts = request.getParts();
        if (parts != null && parts.size() > 0 ){
            for ( Part p: parts) {
                // 一个 Part 实例 就对应着页面上的 一个 <input type="text|password|radio|checkbox|...." >
                System.out.println(p);

                String name = p.getName();
                System.out.println(name +" : ");

                InputStream in = p.getInputStream();
                InputStreamReader reader = new InputStreamReader(in);
                BufferedReader br = new BufferedReader(reader);
                String line ;
                while ((line = br.readLine()) != null){
                    System.out.println(line);
                }
            }
        }
    }
}
